{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.2  Pandas数据结构Series：基本概念及创建】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "由字典创建为：\n",
      " Jack     90.0\n",
      "Marry    92.0\n",
      "Tom      89.0\n",
      "Zack     65.0\n",
      "Name: 作业1, dtype: float64 \n",
      "------\n",
      "由数组创建为：\n",
      " Jack     90.0\n",
      "Tom      89.0\n",
      "Marry    92.0\n",
      "Zack     76.0\n",
      "Name: 作业1, dtype: float64 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：分别由字典、数组的方式，创建以下要求的Series\n",
    "\n",
    "dic = {'Jack':90,'Tom':89,'Marry':92,'Zack':65}\n",
    "ar = np.array([90,89,92,76])\n",
    "print('由字典创建为：\\n',pd.Series(dic, dtype = np.float, name = '作业1'),'\\n------')\n",
    "print('由数组创建为：\\n',pd.Series(ar, index = ['Jack','Tom','Marry','Zack'],dtype = np.float, name = '作业1'),'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.3  Pandas数据结构Series：索引】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建Series为：\n",
      " a     2.016528\n",
      "b    49.894802\n",
      "c    42.833627\n",
      "d    87.053552\n",
      "e    22.330545\n",
      "f     2.067542\n",
      "g    91.332145\n",
      "h    47.239991\n",
      "i    32.474135\n",
      "j    82.116626\n",
      "dtype: float64 \n",
      "------\n",
      "标签为b，c的值为:\n",
      " 49.8948015368 42.8336272643 \n",
      "------\n",
      "Series中第4到6个值为:\n",
      " d    87.053552\n",
      "e    22.330545\n",
      "f     2.067542\n",
      "dtype: float64 \n",
      "------\n",
      "Series中大于50的值为:\n",
      " d    87.053552\n",
      "g    91.332145\n",
      "j    82.116626\n",
      "dtype: float64 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：创建一个Series，包含10个元素，且每个值为0-100的均匀分布随机值，index为a-j，请分别筛选出：\n",
    "# ① 标签为b，c的值为多少\n",
    "# ② Series中第4到6个值是哪些？\n",
    "# ③ Series中大于50的值有哪些？\n",
    "\n",
    "s = pd.Series(np.random.rand(10)*100, index = list('abcdefghij'))\n",
    "print('创建Series为：\\n', s, '\\n------')\n",
    "print('标签为b，c的值为:\\n', s['b'], s['c'],'\\n------')\n",
    "print('Series中第4到6个值为:\\n', s[3:6],'\\n------')\n",
    "print('Series中大于50的值为:\\n', s[s>50],'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.4  Pandas数据结构Series：基本技巧】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建s：\n",
      " a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "f    5\n",
      "g    6\n",
      "h    7\n",
      "i    8\n",
      "j    9\n",
      "dtype: int32 \n",
      "------\n",
      "s修改后：\n",
      " a    100\n",
      "c      2\n",
      "d      3\n",
      "e    100\n",
      "f    100\n",
      "g      6\n",
      "h      7\n",
      "i      8\n",
      "j      9\n",
      "dtype: int32 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：如图创建Series，并按照要求修改得到结果\n",
    "\n",
    "s = pd.Series(np.arange(10), index = list('abcdefghij'))\n",
    "print('创建s：\\n',s,'\\n------')\n",
    "s[['a','e','f']] = 100\n",
    "s.drop('b', inplace=True)\n",
    "print('s修改后：\\n',s,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建s1为：\n",
      " a    5.236400\n",
      "b    7.548774\n",
      "c    0.127353\n",
      "d    2.048674\n",
      "e    9.340298\n",
      "dtype: float64 \n",
      "\n",
      "创建s2为：\n",
      " c    6.314362\n",
      "d    4.572926\n",
      "e    4.834223\n",
      "f    9.144178\n",
      "g    4.307324\n",
      "dtype: float64 \n",
      "------\n",
      "s1+s2为：\n",
      " a          NaN\n",
      "b          NaN\n",
      "c     6.441715\n",
      "d     6.621600\n",
      "e    14.174521\n",
      "f          NaN\n",
      "g          NaN\n",
      "dtype: float64 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业2：已有s1，s2（值为0-10的随机数），请求出s1+s2的值\n",
    "\n",
    "s1 = pd.Series(np.random.rand(5)*10,index = list('abcde'))\n",
    "s2 = pd.Series(np.random.rand(5)*10,index = list('cdefg'))\n",
    "print('创建s1为：\\n',s1,'\\n')\n",
    "print('创建s2为：\\n',s2,'\\n------')\n",
    "print('s1+s2为：\\n',s1+s2,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.5  Pandas数据结构Dataframe：基本概念及创建】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "结果Dataframe为：\n",
      "    four  one  three  two\n",
      "a     4    1      3    2\n",
      "b     5    2      4    3\n",
      "c     6    3      5    4\n",
      "d     7    4      6    5\n",
      "e     8    5      7    6\n"
     ]
    }
   ],
   "source": [
    "# 作业1：用四种不同的方法，创建以下Dataframe（保证columns和index一致，值不做要求）\n",
    "\n",
    "df1 = pd.DataFrame({'one':[1,2,3,4,5],\n",
    "                   'two':[2,3,4,5,6],\n",
    "                   'three':[3,4,5,6,7],\n",
    "                   'four':[4,5,6,7,8]},\n",
    "                  index = list('abcde'))\n",
    "df2 = pd.DataFrame({'one':pd.Series([1,2,3,4,5],index = list('abcde')),\n",
    "                   'two':pd.Series([2,3,4,5,6],index = list('abcde')),\n",
    "                   'three':pd.Series([3,4,5,6,7],index = list('abcde')),\n",
    "                   'four':pd.Series([4,5,6,7,8],index = list('abcde'))})\n",
    "df3 = pd.DataFrame(np.arange(20).reshape(5,4), \n",
    "                   index = list('abcde'),\n",
    "                  columns = ['one','two','three','four'])\n",
    "df4 = pd.DataFrame([{'one':1,'two':2,'three':3,'four':4},\n",
    "                   {'one':2,'two':3,'three':4,'four':5},\n",
    "                   {'one':3,'two':4,'three':5,'four':6},\n",
    "                   {'one':4,'two':5,'three':6,'four':7},\n",
    "                   {'one':5,'two':6,'three':7,'four':8}],\n",
    "                  index = list('abcde'))\n",
    "print('结果Dataframe为：\\n',df4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.6  Pandas数据结构Dataframe：索引】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建Dataframe为：\n",
      "                a          b          c          d\n",
      "one    60.936882  34.198569  86.933961  63.217850\n",
      "two    93.910622   8.843498  12.482240  35.940462\n",
      "three  11.350391  40.704308  50.524502   5.215897\n",
      "four    5.777448  75.515444  96.847913  57.683561 \n",
      "-------\n",
      "b，c列的所有值为:\n",
      "                b          c\n",
      "one    34.198569  86.933961\n",
      "two     8.843498  12.482240\n",
      "three  40.704308  50.524502\n",
      "four   75.515444  96.847913 \n",
      "------\n",
      "第三第四行的值为:\n",
      "                a          b          c          d\n",
      "three  11.350391  40.704308  50.524502   5.215897\n",
      "four    5.777448  75.515444  96.847913  57.683561 \n",
      "------\n",
      "按顺序索引得到two，one行的值为:\n",
      "              a          b          c          d\n",
      "two  93.910622   8.843498  12.482240  35.940462\n",
      "one  60.936882  34.198569  86.933961  63.217850 \n",
      "------\n",
      "大于50的值为:\n",
      "                a          b          c          d\n",
      "one    60.936882        NaN  86.933961  63.217850\n",
      "two    93.910622        NaN        NaN        NaN\n",
      "three        NaN        NaN  50.524502        NaN\n",
      "four         NaN  75.515444  96.847913  57.683561 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：如图创建Dataframe(4*4，值为0-100的随机数)，通过索引得到以下值\n",
    "# ① 索引得到b，c列的所有值\n",
    "# ② 索引得到第三第四行的数据\n",
    "# ③ 按顺序索引得到two，one行的值\n",
    "# ④ 索引得到大于50的值\n",
    "\n",
    "df = df1 = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,\n",
    "                   index = ['one','two','three','four'],\n",
    "                   columns = ['a','b','c','d'])\n",
    "print('创建Dataframe为：\\n',df,'\\n-------')\n",
    "print('b，c列的所有值为:\\n', df[['b','c']],'\\n------')\n",
    "print('第三第四行的值为:\\n', df[2:4],'\\n------')\n",
    "print('按顺序索引得到two，one行的值为:\\n', df.loc[['two','one']],'\\n------')\n",
    "print('大于50的值为:\\n', df[df>50],'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.7  Pandas数据结构Dataframe：基本技巧】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建Dataframe为：\n",
      "           v1         v2         v3\n",
      "a   6.477556   9.470260  99.929419\n",
      "b  47.411645  50.873012  33.376488\n",
      "c  65.374675  23.431663  43.404255 \n",
      "-------\n",
      "按照index降序：\n",
      "           v1         v2         v3\n",
      "c  65.374675  23.431663  43.404255\n",
      "b  47.411645  50.873012  33.376488\n",
      "a   6.477556   9.470260  99.929419 \n",
      "-------\n",
      "按照第二列值大小降序：\n",
      "           v1         v2         v3\n",
      "b  47.411645  50.873012  33.376488\n",
      "c  65.374675  23.431663  43.404255\n",
      "a   6.477556   9.470260  99.929419 \n",
      "-------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：创建一个3*3，值在0-100区间随机值的Dataframe（如图），分别按照index和第二列值大小，降序排序\n",
    "\n",
    "df = pd.DataFrame(np.random.rand(3,3)*100,\n",
    "                 index = ['a','b','c'],\n",
    "                 columns = ['v1','v2','v3'])\n",
    "print('创建Dataframe为：\\n',df,'\\n-------')\n",
    "print('按照index降序：\\n',df.sort_index(ascending = False),'\\n-------')\n",
    "print('按照第二列值大小降序：\\n',df.sort_values(['v2'], ascending = False),'\\n-------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建Dataframe为：\n",
      "           v1         v2\n",
      "a  39.315629  24.044436\n",
      "b  57.688910  22.576572\n",
      "c  43.566194  83.827742\n",
      "d  77.809447  46.222923\n",
      "e  85.141039  44.336434 \n",
      "-------\n",
      "修改后为：\n",
      "             a    b          c          d\n",
      "v1  39.315629  100  43.566194  77.809447\n",
      "v2  24.044436  100  83.827742  46.222923 \n",
      "-------\n"
     ]
    }
   ],
   "source": [
    "#  作业2：创建一个5*2，值在0-100区间随机值的Dataframe（如图）df1，通过修改得到df2\n",
    "\n",
    "df1 = pd.DataFrame(np.random.rand(5,2)*100,\n",
    "                 index = ['a','b','c','d','e'],\n",
    "                 columns = ['v1','v2'])\n",
    "print('创建Dataframe为：\\n',df1,'\\n-------')\n",
    "df2 = df1.T.drop('e',axis = 1)\n",
    "df2['b'] = 100\n",
    "print('修改后为：\\n',df2,'\\n-------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.8  时间模块：datetime】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1、请输出当前时间： 2017-12-28 12:47:03.375475 \n",
      "------\n",
      "2、请输出时间： 2017-05-01 12:30:00 \n",
      "------\n",
      "3、请输出时间： 2000-12-01 00:00:00 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：请调用datatime模块，输出以下时间信息\n",
    "\n",
    "import datetime\n",
    "\n",
    "print('1、请输出当前时间：', datetime.datetime.now(),'\\n------')\n",
    "print('2、请输出时间：', datetime.datetime(2017,5,1,12,30),'\\n------')\n",
    "print('3、请输出时间：', datetime.datetime(2000,12,1),'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "结果为： 2003-01-26 00:00:00\n"
     ]
    }
   ],
   "source": [
    "# 作业2：请创建时间变量‘2000年5月1日’，求出1000天之后是哪年哪月哪日？\n",
    "\n",
    "t1 = datetime.datetime(2000,5,1)\n",
    "print('结果为：',t1+datetime.timedelta(1000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.9  Pandas时刻数据：Timestamp】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建时间列表为：\n",
      " ['2017-12-1', '2017-12-2', '2017-12-3', '2017-12-4', '2017-12-5', '2017-12-6', '2017-12-7', '2017-12-8', '2017-12-9', '2017-12-10', '2017-12-11', '2017-12-12', '2017-12-13', '2017-12-14', '2017-12-15', '2017-12-16', '2017-12-17', '2017-12-18', '2017-12-19', '2017-12-20', '2017-12-21', '2017-12-22', '2017-12-23', '2017-12-24', '2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28', '2017-12-29', '2017-12-30', '2017-12-31'] \n",
      "------\n",
      "转化成DatetimeIndex为：\n",
      " DatetimeIndex(['2017-12-01', '2017-12-02', '2017-12-03', '2017-12-04',\n",
      "               '2017-12-05', '2017-12-06', '2017-12-07', '2017-12-08',\n",
      "               '2017-12-09', '2017-12-10', '2017-12-11', '2017-12-12',\n",
      "               '2017-12-13', '2017-12-14', '2017-12-15', '2017-12-16',\n",
      "               '2017-12-17', '2017-12-18', '2017-12-19', '2017-12-20',\n",
      "               '2017-12-21', '2017-12-22', '2017-12-23', '2017-12-24',\n",
      "               '2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28',\n",
      "               '2017-12-29', '2017-12-30', '2017-12-31'],\n",
      "              dtype='datetime64[ns]', freq=None) \n",
      "------\n",
      "月中日期为：\n",
      " 2017-12-16 00:00:00 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：请通过迭代创建一个时间列表（如图，时间区间为任意一个月，这里可以用for语句），然后转化成DatetimeIndex，并print月中是多少号\n",
    "\n",
    "datelst = []\n",
    "for i in range(1,32):\n",
    "    datelst.append('2017-12-%i' %i)\n",
    "print('创建时间列表为：\\n',datelst,'\\n------')\n",
    "t = pd.to_datetime(datelst)\n",
    "print('转化成DatetimeIndex为：\\n',t,'\\n------')\n",
    "n = (len(t) + 1)/2 - 1\n",
    "print('月中日期为：\\n',t[int(n)],'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "读取txt文件为：\n",
      " ['20150101', '20150102', '20150103', '20150104', '20150105', '20150106', '20150107', '20150108'] \n",
      "------\n",
      "转化成DatetimeIndex为：\n",
      " DatetimeIndex(['2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04',\n",
      "               '2015-01-05', '2015-01-06', '2015-01-07', '2015-01-08'],\n",
      "              dtype='datetime64[ns]', freq=None) \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业2：请如图创建一个包含时间日期的txt文件，通过open语句读取后转化成DatetimeIndex\n",
    "\n",
    "f = open('C:/Users/Hjx/Desktop/date.txt','r')\n",
    "s = f.readline()\n",
    "datelst = s.split(',')\n",
    "print('读取txt文件为：\\n',datelst,'\\n------')\n",
    "t = pd.to_datetime(datelst)\n",
    "print('转化成DatetimeIndex为：\\n',t,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.10  Pandas时间戳索引：DatetimeIndex】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "时间序列1：\n",
      " 2017-01-01    0.578613\n",
      "2017-01-02    0.805522\n",
      "2017-01-03    0.544745\n",
      "2017-01-04    0.524426\n",
      "2017-01-05    0.969018\n",
      "Freq: D, dtype: float64 \n",
      "------\n",
      "时间序列2：\n",
      " 2017-01-31    0.434898\n",
      "2017-04-30    0.826343\n",
      "2017-07-31    0.185842\n",
      "2017-10-31    0.851676\n",
      "Freq: 3M, dtype: float64 \n",
      "------\n",
      "时间序列3：\n",
      "                        value1    value2    value3    value4\n",
      "2017-12-01 00:00:00  0.790031  0.850821  0.596643  0.538425\n",
      "2017-12-01 00:10:00  0.340135  0.167637  0.950665  0.385907\n",
      "2017-12-01 00:20:00  0.789100  0.253647  0.737544  0.263785\n",
      "2017-12-01 00:30:00  0.161515  0.247085  0.114197  0.371345 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：请输出以下时间序列\n",
    "\n",
    "ts1 = pd.Series(np.random.rand(5),\n",
    "                index = pd.date_range('20170101',periods = 5))\n",
    "ts2 = pd.Series(np.random.rand(4),\n",
    "                index = pd.date_range('2017','2018',freq = '3M'))\n",
    "ts3 = pd.DataFrame(np.random.rand(4,4),\n",
    "                   index = pd.date_range('20171201',periods = 4, freq = '10T'),\n",
    "                  columns = ['value1','value2','value3','value4'])\n",
    "print('时间序列1：\\n',ts1,'\\n------')\n",
    "print('时间序列2：\\n',ts2,'\\n------')\n",
    "print('时间序列3：\\n',ts3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建时间序列ts1：\n",
      " 2017-05-01 12:00:00    0.057813\n",
      "2017-05-01 12:10:00    0.806951\n",
      "2017-05-01 12:20:00    0.759841\n",
      "2017-05-01 12:30:00    0.376766\n",
      "2017-05-01 12:40:00    0.877166\n",
      "Freq: 10T, dtype: float64 \n",
      "------\n",
      "转换成ts2：\n",
      " 2017-05-01 12:00:00    0.057813\n",
      "2017-05-01 12:05:00    0.057813\n",
      "2017-05-01 12:10:00    0.806951\n",
      "2017-05-01 12:15:00    0.806951\n",
      "2017-05-01 12:20:00    0.759841\n",
      "2017-05-01 12:25:00    0.759841\n",
      "2017-05-01 12:30:00    0.376766\n",
      "2017-05-01 12:35:00    0.376766\n",
      "2017-05-01 12:40:00    0.877166\n",
      "Freq: 5T, dtype: float64 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业2：按要求创建时间序列ts1，并转换成ts2\n",
    "\n",
    "ts1 = pd.Series(np.random.rand(5),\n",
    "               index = pd.date_range('20170501 12:0:0',periods = 5, freq = '10T'))\n",
    "ts2 = ts1.asfreq('5T','ffill')\n",
    "print('创建时间序列ts1：\\n',ts1,'\\n------')\n",
    "print('转换成ts2：\\n',ts2,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.11  Pandas时期：Period】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "时间序列1：\n",
      " 2017-01    0.652975\n",
      "2017-02    0.709572\n",
      "2017-03    0.449610\n",
      "2017-04    0.882444\n",
      "2017-05    0.734162\n",
      "Freq: M, dtype: float64 \n",
      "------\n",
      "时间序列2：\n",
      " 2017-01-01 00:00    0.971213\n",
      "2017-01-01 02:00    0.737898\n",
      "2017-01-01 04:00    0.832529\n",
      "2017-01-01 06:00    0.551528\n",
      "2017-01-01 08:00    0.067928\n",
      "Freq: 2H, dtype: float64 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：请输出以下时间序列，使用pd.period_range()\n",
    "\n",
    "ts1 = pd.Series(np.random.rand(5),\n",
    "                index = pd.period_range('20170101','20170501',freq = 'M'))\n",
    "ts2 = pd.Series(np.random.rand(5),\n",
    "                index = pd.period_range('20170101',periods = 5,freq = '2H'))\n",
    "print('时间序列1：\\n',ts1,'\\n------')\n",
    "print('时间序列2：\\n',ts2,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.12  时间序列 - 索引及切片】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建时间序列为：\n",
      "                         value1     value2     value3\n",
      "2017-12-01 00:00:00  55.352641  25.429015  75.134377\n",
      "2017-12-01 12:00:00  81.370159  89.312413   6.840683\n",
      "2017-12-02 00:00:00  56.327040  26.171630  75.490264\n",
      "2017-12-02 12:00:00  89.360466   8.899689  36.969172\n",
      "2017-12-03 00:00:00  67.393683  15.611873  93.805499\n",
      "2017-12-03 12:00:00  42.953537  77.599823  15.528796\n",
      "2017-12-04 00:00:00  49.894794  81.597458  39.301740\n",
      "2017-12-04 12:00:00  67.176581  57.610193  35.825823\n",
      "2017-12-05 00:00:00  85.484082  90.029672  60.947450\n",
      "2017-12-05 12:00:00  77.256713  92.711945   8.152771 \n",
      "------\n",
      "前4行的所有值为:\n",
      "                         value1     value2     value3\n",
      "2017-12-01 00:00:00  55.352641  25.429015  75.134377\n",
      "2017-12-01 12:00:00  81.370159  89.312413   6.840683\n",
      "2017-12-02 00:00:00  56.327040  26.171630  75.490264 \n",
      "------\n",
      "2017-12-4 12:00:00的数据为:\n",
      " value1    67.176581\n",
      "value2    57.610193\n",
      "value3    35.825823\n",
      "Name: 2017-12-04 12:00:00, dtype: float64 \n",
      "------\n",
      "2017-12-4 - 2017-12-5的数据为:\n",
      "                         value1     value2     value3\n",
      "2017-12-04 00:00:00  49.894794  81.597458  39.301740\n",
      "2017-12-04 12:00:00  67.176581  57.610193  35.825823\n",
      "2017-12-05 00:00:00  85.484082  90.029672  60.947450\n",
      "2017-12-05 12:00:00  77.256713  92.711945   8.152771 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：如图创建时间序列(10*3，值为0-100的随机数)，通过索引得到以下值\n",
    "# ① 索引得到前4行的所有值\n",
    "# ② 索引得到2017-12-4 12:00:00的数据\n",
    "# ③ 索引得到2017-12-4 - 2017-12-5的数据\n",
    "\n",
    "import datetime\n",
    "ts = pd.DataFrame(np.random.rand(10,3)*100,\n",
    "                   index = pd.date_range('20171201',periods = 10, freq = '12H'),\n",
    "                  columns = ['value1','value2','value3'])\n",
    "print('创建时间序列为：\\n',ts,'\\n------')\n",
    "print('前4行的所有值为:\\n', ts[:3],'\\n------')\n",
    "print('2017-12-4 12:00:00的数据为:\\n', ts.loc['2017-12-04 12:00:00'],'\\n------')\n",
    "print('2017-12-4 - 2017-12-5的数据为:\\n', ts['20171204':'20171205'],'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.13  时间序列 - 重采样】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建时间序列ts1：\n",
      " 2017-01-01    0.804905\n",
      "2017-01-02    0.945006\n",
      "2017-01-03    0.071361\n",
      "2017-01-04    0.831821\n",
      "2017-01-05    0.286604\n",
      "2017-01-06    0.830055\n",
      "2017-01-07    0.546811\n",
      "2017-01-08    0.798976\n",
      "2017-01-09    0.316307\n",
      "2017-01-10    0.817931\n",
      "Freq: D, dtype: float64 \n",
      "------\n",
      "转换成ts2：\n",
      " 2017-01-01    0.607090\n",
      "2017-01-04    0.649494\n",
      "2017-01-07    0.554031\n",
      "2017-01-10    0.817931\n",
      "Freq: 3D, dtype: float64 \n",
      "------\n",
      "转换成ts3：\n",
      " 2017-01-01 00:00:00    0.804905\n",
      "2017-01-01 12:00:00    0.804905\n",
      "2017-01-02 00:00:00    0.945006\n",
      "2017-01-02 12:00:00    0.945006\n",
      "2017-01-03 00:00:00    0.071361\n",
      "2017-01-03 12:00:00    0.071361\n",
      "2017-01-04 00:00:00    0.831821\n",
      "2017-01-04 12:00:00    0.831821\n",
      "2017-01-05 00:00:00    0.286604\n",
      "2017-01-05 12:00:00    0.286604\n",
      "2017-01-06 00:00:00    0.830055\n",
      "2017-01-06 12:00:00    0.830055\n",
      "2017-01-07 00:00:00    0.546811\n",
      "2017-01-07 12:00:00    0.546811\n",
      "2017-01-08 00:00:00    0.798976\n",
      "2017-01-08 12:00:00    0.798976\n",
      "2017-01-09 00:00:00    0.316307\n",
      "2017-01-09 12:00:00    0.316307\n",
      "2017-01-10 00:00:00    0.817931\n",
      "Freq: 12H, dtype: float64 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：按要求创建时间序列ts1，通过降采样和升采样，转换成ts2，ts3\n",
    "\n",
    "ts1 = pd.Series(np.random.rand(10),\n",
    "              index = pd.date_range('20170101',periods = 10, freq = 'D'))\n",
    "ts2 = ts1.resample('3D').mean()\n",
    "ts3 = ts1.resample('12H').ffill()\n",
    "print('创建时间序列ts1：\\n',ts1,'\\n------')\n",
    "print('转换成ts2：\\n',ts2,'\\n------')\n",
    "print('转换成ts3：\\n',ts3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.14  数值计算和统计基础】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建Dataframe为：\n",
      "         key1       key2\n",
      "0  78.873189  75.037939\n",
      "1  10.000713  18.867336\n",
      "2  59.528854  56.019724\n",
      "3  55.161116  54.100441\n",
      "4  24.143033  51.671367 \n",
      "------\n",
      "df[\"key1\"]的均值为：\n",
      " 42.044512818040104 \n",
      "------\n",
      "df[\"key1\"]的中位数为：\n",
      " 39.652074812919636 \n",
      "------\n",
      "df[\"key2\"]的均值为：\n",
      " 51.13936160130839 \n",
      "------\n",
      "df[\"key2\"]的中位数为：\n",
      " 54.10044106375154 \n",
      "------\n",
      "df的累积和为：\n",
      "         key1       key2  key1_cumsum  key2_cumsum\n",
      "0  78.873189  75.037939    78.873189    75.037939\n",
      "1  10.000713  18.867336    88.873902    93.905275\n",
      "2        NaN  56.019724          NaN   149.925000\n",
      "3  55.161116  54.100441   144.035018   204.025441\n",
      "4  24.143033  51.671367   168.178051   255.696808 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：如图创建一个Dataframe（5*2，值为0-100的随机值），并分别计算key1和key2的均值、中位数、累积和\n",
    "\n",
    "df = pd.DataFrame(np.random.rand(5,2)*100,\n",
    "                 columns = ['key1','key2'])\n",
    "print('创建Dataframe为：\\n',df,'\\n------')\n",
    "df['key1'][2] = np.nan\n",
    "df['key1_cumsum'] = df['key1'].cumsum()\n",
    "df['key2_cumsum'] = df['key2'].cumsum()\n",
    "print('df[\"key1\"]的均值为：\\n',df['key1'].mean(),'\\n------')\n",
    "print('df[\"key1\"]的中位数为：\\n',df['key1'].median(),'\\n------')\n",
    "print('df[\"key2\"]的均值为：\\n',df['key2'].mean(),'\\n------')\n",
    "print('df[\"key2\"]的中位数为：\\n',df['key2'].median(),'\\n------')\n",
    "print('df的累积和为：\\n',df,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请随机输入一组元素，用逗号（英文符号）隔开：\n",
      "a,sc,2,2,2,d,s,s,a\n",
      "------\n",
      "该数组不是唯一值数组\n"
     ]
    }
   ],
   "source": [
    "# 作业2：写出一个输入元素直接生成数组的代码块，然后创建一个函数，该函数功能用于判断一个Series是否是唯一值数组，返回“是”和“不是”\n",
    "\n",
    "def f(s):\n",
    "    s2 = s.unique()\n",
    "    if len(s) == len(s2):\n",
    "        print('------\\n该数组是唯一值数组')\n",
    "    else:\n",
    "        print('------\\n该数组不是唯一值数组')\n",
    "\n",
    "d = input('请随机输入一组元素，用逗号（英文符号）隔开：\\n')\n",
    "lst = d.split(',')\n",
    "ds = pd.Series(lst)\n",
    "f(ds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.15  文本数据】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建Dataframe为：\n",
      "   gender    name math english art\n",
      "0      M    Jack   90      90  90\n",
      "1      M     Tom   89      89  89\n",
      "2      F   Marry   90      90  90\n",
      "3      M    Zack   78      78  78\n",
      "4      F  Heheda   60      60  60 \n",
      "------\n",
      "修改后为：\n",
      "   gender    name math english art\n",
      "0      M    Jack   90      90  90\n",
      "1      M     Tom   89      89  89\n",
      "2      F   Marry   90      90  90\n",
      "3      M    Zack   78      78  78\n",
      "4      F  Heheda   60      60  60 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：如图创建一个Dataframe，并分别通过字符串常用方法得到3个Series：\n",
    "# ① name字段首字母全部大写\n",
    "# ② gender字段去除所有空格\n",
    "# ③ score字段按照-拆分，分别是math，english，art三个学分\n",
    "\n",
    "df = pd.DataFrame({'name':['jack','tom','Marry','zack','heheda'],\n",
    "                  'gender':['M ','M','   F','  M ','  F'],\n",
    "                  'score':['90-92-89','89-78-88','90-92-95','78-88-76','60-60-67']})\n",
    "df['name'] = df['name'].str.capitalize()\n",
    "df['gender'] = df['gender'].str.strip()\n",
    "df['math'] = df['score'].str.split('-', expand=True)[0]\n",
    "df['english'] = df['score'].str.split('-', expand=True)[0]\n",
    "df['art'] = df['score'].str.split('-', expand=True)[0]\n",
    "del df['score']\n",
    "print('创建Dataframe为：\\n',df,'\\n------')\n",
    "print('修改后为：\\n',df,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.16  合并 merge、join】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df1为：\n",
      "   key   values1\n",
      "0   a  0.081882\n",
      "1   b  0.988895\n",
      "2   c  0.026287 \n",
      "------\n",
      "创建df2为：\n",
      "   key   values2\n",
      "0   b  0.608940\n",
      "1   c  0.045922\n",
      "2   d  0.050287 \n",
      "------\n",
      "合并df3为：\n",
      "   key   values1   values2\n",
      "0   a  0.081882       NaN\n",
      "1   b  0.988895  0.608940\n",
      "2   c  0.026287  0.045922\n",
      "3   d       NaN  0.050287 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：按要求创建Dataframe df1、df2，并合并成df3\n",
    "\n",
    "df1 = pd.DataFrame({'key':['a','b','c'],\n",
    "                   'values1':np.random.rand(3)})\n",
    "df2 = pd.DataFrame({'key':['b','c','d'],\n",
    "                   'values2':np.random.rand(3)})\n",
    "df3 = pd.merge(df1,df2,on='key',how='outer')\n",
    "\n",
    "print('创建df1为：\\n',df1,'\\n------')\n",
    "print('创建df2为：\\n',df2,'\\n------')\n",
    "print('合并df3为：\\n',df3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df1为：\n",
      "   lkey   values1\n",
      "0    a  0.777625\n",
      "1    b  0.102231\n",
      "2    c  0.543267 \n",
      "------\n",
      "创建df2为：\n",
      "   rkey   values2\n",
      "0    b  0.745419\n",
      "1    c  0.276994\n",
      "2    d  0.423683 \n",
      "------\n",
      "合并df3为：\n",
      "   lkey   values1 rkey   values2\n",
      "0    a  0.777625  NaN       NaN\n",
      "1    b  0.102231    b  0.745419\n",
      "2    c  0.543267    c  0.276994 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业2：按要求创建Dataframe df1、df2，并合并成df3\n",
    "\n",
    "df1 = pd.DataFrame({'lkey':['a','b','c'],\n",
    "                   'values1':np.random.rand(3)})\n",
    "df2 = pd.DataFrame({'rkey':['b','c','d'],\n",
    "                   'values2':np.random.rand(3)})\n",
    "df3 = pd.merge(df1,df2,left_on='lkey',right_on='rkey',how='left')\n",
    "\n",
    "print('创建df1为：\\n',df1,'\\n------')\n",
    "print('创建df2为：\\n',df2,'\\n------')\n",
    "print('合并df3为：\\n',df3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df1为：\n",
      "   key   values1\n",
      "0   a  0.638707\n",
      "1   b  0.346130\n",
      "2   c  0.216459 \n",
      "------\n",
      "创建df2为：\n",
      "     values2  values3\n",
      "b  0.526828        5\n",
      "c  0.416468        6\n",
      "d  0.957053        7 \n",
      "------\n",
      "合并df3为：\n",
      "   key   values1   values2  values3\n",
      "1   b  0.346130  0.526828        5\n",
      "2   c  0.216459  0.416468        6 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业3：按要求创建Dataframe df1、df2，并合并成df3\n",
    "\n",
    "df1 = pd.DataFrame({'key':['a','b','c'],\n",
    "                   'values1':np.random.rand(3)})\n",
    "df2 = pd.DataFrame({'values2':np.random.rand(3),\n",
    "                   'values3':[5,6,7]},\n",
    "                  index = ['b','c','d'])\n",
    "df3 = pd.merge(df1,df2,left_on='key',right_index=True)\n",
    "\n",
    "print('创建df1为：\\n',df1,'\\n------')\n",
    "print('创建df2为：\\n',df2,'\\n------')\n",
    "print('合并df3为：\\n',df3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.17  连接与修补 concat、combine_first】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df1为：\n",
      "     values1   values2\n",
      "a  0.447342  0.680339\n",
      "b  0.226332  0.354134\n",
      "c  0.686542  0.407370\n",
      "d  0.033940  0.962322 \n",
      "------\n",
      "创建df2为：\n",
      "     values1   values2\n",
      "e  0.045157  0.416692\n",
      "f  0.714113  0.902906\n",
      "g  0.105140  0.127267\n",
      "h  0.085265  0.484986 \n",
      "------\n",
      "连接df3为：\n",
      "     values1   values2\n",
      "a  0.447342  0.680339\n",
      "b  0.226332  0.354134\n",
      "c  0.686542  0.407370\n",
      "d  0.033940  0.962322\n",
      "e  0.045157  0.416692\n",
      "f  0.714113  0.902906\n",
      "g  0.105140  0.127267\n",
      "h  0.085265  0.484986 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：按要求创建Dataframe df1、df2，并连接成df3\n",
    "\n",
    "df1 = pd.DataFrame(np.random.rand(4,2),\n",
    "                  index = list('abcd'),\n",
    "                  columns = ['values1','values2'])\n",
    "df2 = pd.DataFrame(np.random.rand(4,2),\n",
    "                  index = list('efgh'),\n",
    "                  columns = ['values1','values2'])\n",
    "df3 = pd.concat([df1,df2])\n",
    "\n",
    "print('创建df1为：\\n',df1,'\\n------')\n",
    "print('创建df2为：\\n',df2,'\\n------')\n",
    "print('连接df3为：\\n',df3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df1为：\n",
      "     values1   values2\n",
      "a  0.593720  0.755037\n",
      "b       NaN  0.457937\n",
      "c       NaN  0.382456\n",
      "d  0.250054  0.176994 \n",
      "------\n",
      "创建df2为：\n",
      "    values1  values2\n",
      "a        0        1\n",
      "b        2        3\n",
      "c        4        5\n",
      "d        6        7 \n",
      "------\n",
      "df1修补后为：\n",
      "     values1   values2\n",
      "a  0.593720  0.755037\n",
      "b  2.000000  0.457937\n",
      "c  4.000000  0.382456\n",
      "d  0.250054  0.176994 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业2：按要求创建Dataframe df1、df2，并用df2的值修补df1，生成df3\n",
    "\n",
    "df1 = pd.DataFrame(np.random.rand(4,2),\n",
    "                  index = list('abcd'),\n",
    "                  columns = ['values1','values2'])\n",
    "df1['values1'].loc[['b','c']] = np.nan\n",
    "df2 = pd.DataFrame(np.arange(8).reshape(4,2),\n",
    "                  index = list('abcd'),\n",
    "                  columns = ['values1','values2'])\n",
    "df3 = df1.combine_first(df2)\n",
    "\n",
    "print('创建df1为：\\n',df1,'\\n------')\n",
    "print('创建df2为：\\n',df2,'\\n------')\n",
    "print('df1修补后为：\\n',df3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.19  数据分组】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df1为：\n",
      "     values1   values2\n",
      "a  0.632057  0.078720\n",
      "b  0.527422  0.331507\n",
      "c  0.126908  0.896146\n",
      "d  0.385836  0.609255 \n",
      "------\n",
      "创建df2为：\n",
      "     values1   values2\n",
      "e  0.990162  0.818098\n",
      "f  0.515815  0.433778\n",
      "g  0.474512  0.428800\n",
      "h  0.576840  0.940886 \n",
      "------\n",
      "连接df3为：\n",
      "     values1   values2\n",
      "a  0.632057  0.078720\n",
      "b  0.527422  0.331507\n",
      "c  0.126908  0.896146\n",
      "d  0.385836  0.609255\n",
      "e  0.990162  0.818098\n",
      "f  0.515815  0.433778\n",
      "g  0.474512  0.428800\n",
      "h  0.576840  0.940886 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：按要求创建Dataframe df1、df2，并连接成df3\n",
    "\n",
    "df1 = pd.DataFrame(np.random.rand(4,2),\n",
    "                  index = list('abcd'),\n",
    "                  columns = ['values1','values2'])\n",
    "df2 = pd.DataFrame(np.random.rand(4,2),\n",
    "                  index = list('efgh'),\n",
    "                  columns = ['values1','values2'])\n",
    "df3 = pd.concat([df1,df2])\n",
    "\n",
    "print('创建df1为：\\n',df1,'\\n------')\n",
    "print('创建df2为：\\n',df2,'\\n------')\n",
    "print('连接df3为：\\n',df3,'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.19  数据分组】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df为：\n",
      "        A  B   C         D         E\n",
      "0    one  h  10 -0.085340  0.420645\n",
      "1    two  h  12  2.373044  0.664479\n",
      "2  three  h  14  0.553483  0.988042\n",
      "3    one  h  16  0.155289  0.184052\n",
      "4    two  f  18  1.942460  0.037124\n",
      "5  three  f  20 -0.085759  0.658828\n",
      "6    one  f  22 -1.368377  0.334869\n",
      "7    two  f  24 -1.101152  0.254488 \n",
      "------\n",
      "以A分组，求出C,D的分组平均值为：\n",
      "         C         D         E\n",
      "A                            \n",
      "one    16 -0.432809  0.313189\n",
      "three  17  0.233862  0.823435\n",
      "two    18  1.071450  0.318697 \n",
      "------\n",
      "以A,B分组，求出D,E的分组求和为：\n",
      "           C         D         E\n",
      "A     B                        \n",
      "one   f  22 -1.368377  0.334869\n",
      "      h  26  0.069949  0.604697\n",
      "three f  20 -0.085759  0.658828\n",
      "      h  14  0.553483  0.988042\n",
      "two   f  42  0.841308  0.291611\n",
      "      h  12  2.373044  0.664479 \n",
      "------\n",
      "以A分组，筛选出分组后的第一组数据为：\n",
      " {'three': [2, 5], 'two': [1, 4, 7], 'one': [0, 3, 6]} \n",
      "------\n",
      "按照数值类型分组为：\n",
      "    int32   float64  object\n",
      "0     10  0.335305    oneh\n",
      "1     12  3.037522    twoh\n",
      "2     14  1.541526  threeh\n",
      "3     16  0.339341    oneh\n",
      "4     18  1.979583    twof\n",
      "5     20  0.573069  threef\n",
      "6     22 -1.033508    onef\n",
      "7     24 -0.846665    twof \n",
      "------\n",
      "将C,D作为一组分出来，并计算求和为：\n",
      "            r\n",
      "0   9.914660\n",
      "1  14.373044\n",
      "2  14.553483\n",
      "3  16.155289\n",
      "4  19.942460\n",
      "5  19.914241\n",
      "6  20.631623\n",
      "7  22.898848 \n",
      "------\n",
      "以B分组，求出每组的均值，求和，最大值，最小值：\n",
      "      C                       D                                       E  \\\n",
      "  mean sum amax amin      mean       sum      amax      amin      mean   \n",
      "B                                                                        \n",
      "f   21  84   24   18 -0.153207 -0.612828  1.942460 -1.368377  0.321327   \n",
      "h   13  52   16   10  0.749119  2.996477  2.373044 -0.085340  0.564304   \n",
      "\n",
      "                                 \n",
      "        sum      amax      amin  \n",
      "B                                \n",
      "f  1.285308  0.658828  0.037124  \n",
      "h  2.257218  0.988042  0.184052   \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：按要求创建Dataframe df，并通过分组得到以下结果\n",
    "# ① 以A分组，求出C,D的分组平均值\n",
    "# ② 以A,B分组，求出D,E的分组求和\n",
    "# ③ 以A分组，得到所有分组，以字典显示\n",
    "# ④ 按照数值类型分组，求和\n",
    "# ⑤ 将C,D作为一组分出来，并计算求和\n",
    "# ⑥ 以B分组，求出每组的均值，求和，最大值，最小值\n",
    "\n",
    "df = pd.DataFrame({'A' : ['one', 'two', 'three', 'one','two', 'three', 'one', 'two'],\n",
    "                   'B' : ['h', 'h', 'h', 'h', 'f', 'f', 'f', 'f'],\n",
    "                   'C' : np.arange(10,26,2),\n",
    "                   'D' : np.random.randn(8),\n",
    "                   'E':np.random.rand(8)})\n",
    "\n",
    "\n",
    "print('创建df为：\\n',df,'\\n------')\n",
    "print('以A分组，求出C,D的分组平均值为：\\n',df.groupby('A').mean(),'\\n------')\n",
    "print('以A,B分组，求出D,E的分组求和为：\\n',df.groupby(['A','B']).sum(),'\\n------')\n",
    "print('以A分组，筛选出分组后的第一组数据为：\\n',df.groupby('A').groups,'\\n------')\n",
    "print('按照数值类型分组为：\\n',df.groupby(df.dtypes,axis=1).sum(),'\\n------')\n",
    "print('将C,D作为一组分出来，并计算求和为：\\n',df.groupby({'C':'r','D':'r'},axis=1).sum(),'\\n------')\n",
    "print('以B分组，求出每组的均值，求和，最大值，最小值：\\n',df.groupby('B').agg([np.mean,np.sum,np.max,np.min]),'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.20  分组转换及一般性“拆分-应用-合并”】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df为：\n",
      "       data1     data2 key\n",
      "0  0.298507  0.481976   a\n",
      "1  0.761940  0.472252   a\n",
      "2  0.639491  0.964618   b\n",
      "3  0.238919  0.756300   b\n",
      "4  0.231337  0.617190   a\n",
      "5  0.681743  0.906671   b\n",
      "6  0.601592  0.798819   a\n",
      "7  0.071703  0.109292   b \n",
      "------\n",
      "求和且合并之后结果为：\n",
      "       data1     data2 key  data1_mean  data2_mean\n",
      "0  0.298507  0.481976   a    0.473344    0.592559\n",
      "1  0.761940  0.472252   a    0.473344    0.592559\n",
      "2  0.639491  0.964618   b    0.407964    0.684220\n",
      "3  0.238919  0.756300   b    0.407964    0.684220\n",
      "4  0.231337  0.617190   a    0.473344    0.592559\n",
      "5  0.681743  0.906671   b    0.407964    0.684220\n",
      "6  0.601592  0.798819   a    0.473344    0.592559\n",
      "7  0.071703  0.109292   b    0.407964    0.684220 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：按要求创建Dataframe df，通过key分组求和，并将求和结果并在原df中\n",
    "\n",
    "df = pd.DataFrame({'data1':np.random.rand(8),\n",
    "                  'data2':np.random.rand(8),\n",
    "                  'key':list('aabbabab')})\n",
    "\n",
    "print('创建df为：\\n',df,'\\n------')\n",
    "df_ = df.groupby('key').transform(np.mean)\n",
    "print('求和且合并之后结果为：\\n',df.join(df_,rsuffix='_mean'),'\\n------')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "'''\n",
    "【课程2.21  透视表及交叉表】 课程作业\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "创建df为：\n",
      "        A  B   C         D         E\n",
      "0    one  h  10  0.456511  0.713847\n",
      "1    two  h  12 -1.807333  0.852110\n",
      "2  three  h  14  0.526257  0.942896\n",
      "3    one  h  16 -0.796059  0.015267\n",
      "4    two  f  18  0.819476  0.838997\n",
      "5  three  f  20 -0.185152  0.814255\n",
      "6    one  f  22 -0.736728  0.856365\n",
      "7    two  f  24  1.318259  0.194405 \n",
      "------\n",
      "以A列聚合，求出C,D的平均值为：\n",
      "         C         D\n",
      "A                  \n",
      "one    16 -0.358759\n",
      "three  17  0.170552\n",
      "two    18  0.110134 \n",
      "------\n",
      "以A,B列聚合，求出D,E的均值、求和为：\n",
      "              mean                 sum          \n",
      "                D         E         D         E\n",
      "A     B                                        \n",
      "one   f -0.736728  0.856365 -0.736728  0.856365\n",
      "      h -0.169774  0.364557 -0.339548  0.729114\n",
      "three f -0.185152  0.814255 -0.185152  0.814255\n",
      "      h  0.526257  0.942896  0.526257  0.942896\n",
      "two   f  1.068867  0.516701  2.137735  1.033402\n",
      "      h -1.807333  0.852110 -1.807333  0.852110 \n",
      "------\n",
      "以B聚合，计算A列的元素频率为：\n",
      " A  one  three  two\n",
      "B                 \n",
      "f    1      1    2\n",
      "h    2      1    1 \n",
      "------\n"
     ]
    }
   ],
   "source": [
    "# 作业1：按要求创建Dataframe df，并通过数据透视表得到以下结果\n",
    "# ① 以A列聚合，求出C,D的平均值\n",
    "# ② 以A,B列聚合，求出D,E的均值、求和\n",
    "# ③ 以B聚合，计算A列的元素频率\n",
    "\n",
    "df = pd.DataFrame({'A' : ['one', 'two', 'three', 'one','two', 'three', 'one', 'two'],\n",
    "                   'B' : ['h', 'h', 'h', 'h', 'f', 'f', 'f', 'f'],\n",
    "                   'C' : np.arange(10,26,2),\n",
    "                   'D' : np.random.randn(8),\n",
    "                   'E':np.random.rand(8)})\n",
    "\n",
    "\n",
    "print('创建df为：\\n',df,'\\n------')\n",
    "print('以A列聚合，求出C,D的平均值为：\\n',pd.pivot_table(df,values=['C','D'],index='A',aggfunc=np.mean),'\\n------')\n",
    "print('以A,B列聚合，求出D,E的均值、求和为：\\n',pd.pivot_table(df,values=['D','E'],index=['A','B'],aggfunc=[np.mean,np.sum]),'\\n------')\n",
    "print('以B聚合，计算A列的元素频率为：\\n',pd.crosstab(df['B'],df['A']),'\\n------')"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
